'use strict';
require([
        'jquery',
        "editormd",
        'jquery.extern',
        'lhgdialog.lang',
        'lhgdialog.base',
        "../mdeditor/plugins/link-dialog/link-dialog",
        "../mdeditor/plugins/reference-link-dialog/reference-link-dialog",
        "../mdeditor/plugins/image-dialog/image-dialog",
        "../mdeditor/plugins/code-block-dialog/code-block-dialog",
        "../mdeditor/plugins/table-dialog/table-dialog",
        "../mdeditor/plugins/emoji-dialog/emoji-dialog",
        "../mdeditor/plugins/goto-line-dialog/goto-line-dialog",
        "../mdeditor/plugins/help-dialog/help-dialog",
        "../mdeditor/plugins/html-entities-dialog/html-entities-dialog",
        "../mdeditor/plugins/preformatted-text-dialog/preformatted-text-dialog"
    ], function ($, editormd) {

        $(document).keydown(function (event) {
                if ((event.ctrlKey || event.metaKey) && event.which == 83) {
                    event.preventDefault();

                    try {
                        window.parent.angular.element(window.parent.$('#command-submit')).scope().submit();
                    } catch (e) {
                    }

                    return false;
                }
                if (event.which == 122) {
                    event.preventDefault();
                    window.parent.angular.element(window.parent.$('.btn-fullscreen')).scope().fullscreen();
                    return false;
                }
            }
        );

        $(function () {

            editormd.loadCSS(TPX.PATH_ASSERTS + "/mdeditor/lib/codemirror/addon/fold/foldgutter");

            window.parent.markdownEditor = editormd("markdown_editor", {
                width: "100%",
                path: TPX.PATH_ASSERTS + '/mdeditor/lib/',
                //theme: "dark",
                tex: true,
                emoji: false,
                taskList: true,
                flowChart: true,
                sequenceDiagram: true,
                htmlDecode : "style,script,iframe|on*",
                onload: function () {
                    var markdown = this;
                    this.fullscreen();
                    this.addKeyMap({
                        "Ctrl-S": function (cm) {
                            //window.parent.angular.element(window.parent.$('#command-submit')).scope().submit();
                        }
                    });

                    // 粘贴上传
                    $('#markdown_editor').attr('contenteditable', true);
                    $('#markdown_editor').on('paste', function (e) {

                        //支持clipboardData浏览器
                        var clipboardData, items, item;
                        if (e && (clipboardData = e.originalEvent.clipboardData)
                            && (items = clipboardData.items ) && ( item = items[0] )
                        ) {
                            if (item.kind == 'file' && item.type.match(/^image\//i)) {
                                var blob = item.getAsFile(), reader = new FileReader();

                                var waiting = null;
                                var waiting_start = function () {
                                    waiting = $.dialog.tips(lhgdialog_lang.LOADING, 10, 'loading.gif');
                                };
                                var waiting_timeout = setTimeout(function () {
                                    if (waiting) {
                                        waiting.close();
                                        waiting = null;
                                    }
                                    $.dialog.alert(lhgdialog_lang.TIMEOUT);
                                }, 30000);
                                var waiting_end = function () {
                                    if (waiting) {
                                        waiting.close();
                                        waiting = null;
                                    }
                                    clearTimeout(waiting_timeout);
                                };

                                waiting_start();

                                reader.onload = function () {
                                    var xhr = new XMLHttpRequest(),
                                        fd = new FormData();
                                    xhr.open('POST', $.urlBuild('system', 'uploadhandle', {action: 'uploadscrawl'}), true);
                                    xhr.onload = function () {
                                        waiting_end();
                                        var objResults = $.parseJSON(xhr.responseText);
                                        if (objResults.state == 'SUCCESS') {
                                            markdown.insertValue('![](http://' + window.document.domain + TPX.PATH_ROOT + '/' + objResults.url + ')');
                                        } else {
                                            alert(objResults.state);
                                        }
                                    };
                                    fd.append('upfile', this.result);
                                    xhr.send(fd);
                                };
                                reader.readAsDataURL(blob);
                                return false;
                            } else {
                                return true;
                            }
                        }

                        //其他浏览器在粘贴后插入指定dom来判断
                        /*
                        var self = this;
                        document.execCommand('insertHTML', false, '<span id="tecmz-paste"></span>');
                        var pasteHelper = $(self).find('#tecmz-paste');
                        pasteHelper.focus();
                        setTimeout(function () {
                            var targetImg = pasteHelper.prev('img').length ? pasteHelper.prev('img') : pasteHelper.prev().find('img:last');

                        }, 0);
                        */

                    });

                },
                toolbarIcons: function () {
                    return [
                        //"undo", "redo", "|",
                        "bold", 'del', 'italic', 'quote', 'uppercase', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'list-ul', 'list-ol', "hr",
                        'link',
                        //'reference-link',
                        'image', 'code',
                        //'preformatted-text',
                        'code-block', 'table', 'datetime',
                        //'emoji',
                        'html-entities',
                        //'pagebreak',
                        'goto-line', 'watch',
                        //'unwatch',
                        'preview', 'search',
                        //'fullscreen',
                        //'clear',
                        'help'
                    ];
                },
                imageUpload: true,
                imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                imageUploadURL: TPX.PATH_ROOT + '/?s=doc/upload_image'
            });

        });

    }
);

